from flask_login import current_user

from app.app_init import app
from flask import render_template, abort, flash, redirect, url_for

from forms.delete_article_form import DeleteArticleForm
from services import article_service
from forms.login_form import LoginForm
from services.user_service import UserService


@app.route('/', methods=['GET', 'POST'])
@app.route('/index.html', methods=['GET', 'POST'])
def home_page():
    if current_user.is_authenticated:
        delete_article_form = DeleteArticleForm()
        if delete_article_form.validate_on_submit():
            res = article_service.ArticleService().delete_article(int(delete_article_form.article_id.data))
            if res:
                flash('删除成功', category='success')

    articles = article_service.ArticleService().get_articles()
    for article in articles:
        if len(article.content) < 80:
            pass
        else:
            article.content = article.content[:80]

    if current_user.is_authenticated:
        return render_template('index.html', articles=articles, delete_article_form=delete_article_form)
    return render_template('index.html', articles=articles)



@app.route('/about.html')
def about_page():
    return render_template('about.html')


@app.route('/article/<article_id>.html')
def article_page(article_id):
    article = article_service.ArticleService().get_article(id=article_id)
    if article:
        return render_template('article.html', article=article)

    abort(404)



@app.route('/login.html', methods=['GET', 'POST'])
def login_page():
    form = LoginForm()
    if form.validate_on_submit():
        result = UserService().do_login(username=form.username.data, password=form.password.data)
        if result:
            flash(message=f'欢迎{form.username.data}', category='success')
            return redirect(url_for('home_page'))
        else:
            flash(message=f'用户名或密码错误,请重试', category='danger')
    return render_template('login.html', form=form)

@app.route('/logout.html')
def logout_page():
    UserService().do_logout()
    return redirect(url_for('home_page'))

